package governor

import (
	"encoding/json"
	"net/http"
	"net/http/pprof"
	"os"
	"runtime/debug"

	"gitee.com/zawei/yggdrasil/pkg"
	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/pkg/log"
	"gitee.com/zawei/yggdrasil/pkg/transport/server"
)

func init() {
	cfg := &Config{}
	if err := config.Get("server.governor").Scan(cfg); err != nil {
		log.Fatalf("fault to scan config[%s], error: %s", "server.governor", err.Error())
	}
	server.RegisterServer(cfg.Build())
	handleFunc()
}

func handleFunc() {
	// 获取全部治理路由
	HandleFunc("/routes", func(resp http.ResponseWriter, req *http.Request) {
		_ = json.NewEncoder(resp).Encode(routes)
	})

	HandleFunc("/debug/pprof/", pprof.Index)
	HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	HandleFunc("/debug/pprof/profile", pprof.Profile)
	HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	HandleFunc("/debug/pprof/trace", pprof.Trace)
	HandleFunc("/configs", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		encoder := json.NewEncoder(w)
		if r.URL.Query().Get("pretty") == "true" {
			encoder.SetIndent("", "    ")
		}
		_ = encoder.Encode(config.Map())
	})
	HandleFunc("/debug/env", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		encoder := json.NewEncoder(w)
		if r.URL.Query().Get("pretty") == "true" {
			encoder.SetIndent("", "    ")
		}
		_ = encoder.Encode(os.Environ())
	})
	HandleFunc("/build/info", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		encoder := json.NewEncoder(w)
		if r.URL.Query().Get("pretty") == "true" {
			encoder.SetIndent("", "    ")
		}
		serverStats := map[string]string{
			"name":             pkg.AppName(),
			"appID":            pkg.AppID(),
			"appVersion":       pkg.AppVersion(),
			"frameworkVersion": pkg.FrameworkVersion(),
			"buildTime":        pkg.BuildTime(),
			"startTime":        pkg.StartTime(),
			"hostname":         pkg.Hostname(),
			"goVersion":        pkg.GoVersion(),
		}
		_ = encoder.Encode(serverStats)
	})

	if info, ok := debug.ReadBuildInfo(); ok {
		HandleFunc("/modInfo", func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(200)
			encoder := json.NewEncoder(w)
			if r.URL.Query().Get("pretty") == "true" {
				encoder.SetIndent("", "    ")
			}
			_ = encoder.Encode(info)
		})
	}

}
